package fischl.douyuApi;

import fischl.log.Log;
import fischl.log.LogFactory;
import okhttp3.Request;
import fischl.Global;
import fischl.douyuApi.model.*;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public final class DouyuService {
  private static final Log log = LogFactory.get("douyuService");

  public static List<Danmu> getDanmuByHashId(String videoHashId) {
    log.i("collecting danmu in video " + videoHashId);
    String startTime = "";
    List<Danmu> danmus = new ArrayList<>();
    while (true) {
      Call<Res<DanmuPage>> call = Global.douyuApi().getDanmuList(videoHashId, startTime);
      DanmuPage res = execute(call);
      if(res == null) break;
      danmus.addAll(res.list);
      if (res.end_time == -1) {
        break;
      } else {
        startTime = "" + res.end_time;
      }
    }
    return danmus;
  }

  public String getUpId(String vid) {
    Request request = new Request.Builder().get().url("https://v.douyu.com/show/" + vid).build();
    String html = execute(request);

    // 获取up id
    String mark = "\"up_id\":\"";
    int index = html.indexOf(mark) + mark.length();
    return html.substring(index, html.indexOf('"', index));
  }

  /**
   * 获取指定作者的最后一条视频数据
   *
   * @param upId 作者id
   */
  public static VideoP getLastVideo(String upId) {
    Call<Res<VideoPList>> call = Global.douyuApi().getLastVideo(upId);
    VideoPList result = execute(call);
    if (result == null) return null;
    if (result.list == null) return null;
    if (result.list.isEmpty()) return null;
    return result.list.get(0);
  }

  // Nullable
  public static <T> T execute(Call<Res<T>> call) {
    Response<Res<T>> response;
    try {
      response = call.execute();
    } catch (IOException e) {
      log.e("IOException while execute against " + call.request().url(), e);
      return null;
    }
    if (!response.isSuccessful()) {
      log.e("response failed by code {} with url {}", response.code(), call.request().url());
      return null;
    }
    if (response.body() == null) {
      log.e("response failed by body == null with url {}", call.request().url());
      return null;
    }
    if (response.body().error != 0) {
      log.e("response failed by douyu errorCode == {} with url {}", response.body().error,
        call.request().url());
      return null;
    }
    return response.body().data;
  }


  /**
   * 获取视频分p数据
   *
   * @param hashId 其中的一个视频hashId
   * @param upId   视频作者id
   */
  public static VideoDateData getVideosByP(String hashId, String upId) {
    Call<Res<VideoDateData>> call = Global.douyuApi().getVideoSlices(hashId, upId);
    return execute(call);
  }

  public static String execute(Request request) {
    try (okhttp3.Response r = Global.okHttpClient().newCall(request).execute()) {
      if (!r.isSuccessful() || r.body() == null) {
        String failReason = !r.isSuccessful() ? "code=" + r.code() + " message=" + r.message() :
          "body == null";
        System.out.println("failed access " + request.url() + " by " + failReason);
        return null;
      }
      return r.body().string();
    } catch (IOException e) {
      System.out.println("failed access " + request.url());
      e.printStackTrace();
      return null;
    }
  }
}
